package com.ycsj.goldmedalnewconcept.master.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.mob.MobSDK;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.view.dialog.AlertDialogUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.RedPackageResponse;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.fragment.LazyBaseFragment;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import okhttp3.Call;

import static java.lang.Float.parseFloat;

public class RedPackageFragment extends LazyBaseFragment implements
        View.OnClickListener, OnDateSetListener {

    // 红包金额
    private EditText etMoney;

    // 红包个数
    private EditText etHbgs;

    // 时效限制
    private TextView tvSxxz;

    // 红包主题
    private EditText etHbzt;

    // 塞进红包的按钮
    private Button btCommit;
    // 总金额
    private String money;
    // 红包个数
    private String redCount;
    // 时效限制
    private String time;
    // 红包主题
    private String hbzt = "学有所成,前程似锦!";
    // 上传的文件地址
    private String filePath;

    // 时间选择控件
    TimePickerView pvTime;

    private String pngName;

    private String themeId = "1";

    private String imagePath;

    private Intent intent;

    protected static final int THEME_ID = 0;

    private String redid;

    private String logo;

    private LinearLayout ll_loading;

    //时间选择器
    private TimePickerDialog mDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_red_package;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        // 初始化控件
        initView(view);

        //初始化日期
        showDatePick();
    }

    /**
     * 初始化控件
     */
    private void initView(View view) {
        tvSxxz = view.findViewById(R.id.tv_sxxz);
        etMoney = view.findViewById(R.id.et_money);
        etHbgs = view.findViewById(R.id.et_hbgs);
        etHbzt = view.findViewById(R.id.et_hbzt);
        btCommit = view.findViewById(R.id.bt_sjhb);
        ll_loading = view.findViewById(R.id.ll_loading);


        tvSxxz.setOnClickListener(this);
        btCommit.setOnClickListener(this);


        if (TextUtils.isEmpty(AccountUtils.getLogo(getActivity()))) {
            logo = "http://139.129.57.83:8080/Appandroid/redbag.png";
        } else {
            TextUtils.isEmpty(AccountUtils.getLogo(getActivity()));
        }
    }


    @Override
    public void onResume() {
        imagePath = SPUtil.getString(getActivity(), "imagePath");
        themeId = SPUtil.getString(getActivity(), "themeId");

        Log.e("test", "imagePath" + imagePath);
        Log.e("test", "themeId" + themeId);

        super.onResume();
    }


    /**
     * 选择日期的方法
     */
    private void showDatePick() {

        long oneYears = 2L * 365 * 1000 * 60 * 60 * 24L;

        long oneHour = 1L * 1000 * 60 * 60;

        mDialog = new TimePickerDialog.Builder()
                .setCallBack(this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择日期和时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
//                .setHourText("时")
//                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis() )
                .setMaxMillseconds(System.currentTimeMillis() + oneYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_toolbar_bg))
//                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.YEAR_MONTH_DAY)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
                .setWheelItemTextSize(12)
                .build();

        //默认当前时间
//		currtime = getDateToString(System.currentTimeMillis() + 60 * 1000);
        time = getDateToString(System.currentTimeMillis() + 60 * 1000);
        Log.i("test", "time=" + time);
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        time = getDateToString(millseconds);
        tvSxxz.setText(time);
    }


    public String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_sxxz:
                // 时效限制
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

                mDialog.show(getFragmentManager(), "yyyy-MM-dd");

                break;
            case R.id.bt_sjhb:
                // 塞进红包
                judgeAll();
                break;
        }
    }

    /**
     * 点击塞进红包后按钮后的判断完整性方法
     */
    private void judgeAll() {

        // 获取金额
        money = etMoney.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            Toast.makeText(getActivity(), "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }

        // 红包个数
        redCount = etHbgs.getText().toString().trim();
        if (TextUtils.isEmpty(redCount) || Integer.parseInt(redCount) <= 0) {
            Toast.makeText(getActivity(), "您输入的红包金额必须保证每人最少可以领取1元", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        // 时效限制时间
        time = tvSxxz.getText().toString().trim();
        Log.e("time", time);
        if (TextUtils.isEmpty(time)) {
            Toast.makeText(getActivity(), "请选择红包的截止时间", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        if ("红包有效期截止时间".equals(time)) {
            Toast.makeText(getActivity(), "请选择红包的截止时间", Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        // 红包主题
        hbzt = etHbzt.getText().toString().trim();

        // 判断总金额/红包个数的值是否大于1,保证每个人至少能拿到1块钱以上的红包
        float getMoney = Float.parseFloat(money) / parseFloat(redCount);
        if (getMoney < 1) {

            // 请保证每个人至少能得到一块钱红包
            moneydialog();

            return;
        }
        dialog();
    }

    private void dialog() {

        AlertDialogUtil.showAlertDialog(true, getActivity(), "此红包为拼手气红包，是否确认发送此红包", new AlertDialogUtil.onListener() {
            @Override
            public void onClickOk() {
                ll_loading.setVisibility(ll_loading.VISIBLE);
                if (hbzt == null || "".equals(hbzt)) {
                    hbzt = "学有所成,前程似锦!";
                }
                if (themeId == null || "".equals(themeId)) {
                    themeId = "1";
                }

                // 请求服务器上传用户填写的相关信息
                if (imagePath == null || "".equals(imagePath)) {
                    creatRedPackage();// 无编辑自定义模板图片
                } else {
                    File f = new File(getActivity().getCacheDir(), imagePath);

                    creatImageRedPackage();
                }
            }

            @Override
            public void onClickDismiss() {
            }
        });


    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        } else {
            sdDir = getActivity().getFilesDir();
        }
        return sdDir.toString();
    }


    /**
     * 有图片红包
     */
    private void creatImageRedPackage() {

        String path = getSDPath() + "/goldupload/" + imagePath + ".png";
        File f = new File(path);
        String[] split = path.split("\\/");
        String name = split[split.length - 1];


        Map<String, String> map = new HashMap<>();
        map.put("type", "10");
        map.put("rtype", "1");
        map.put("c", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));
        map.put("money", money);
        map.put("persons", redCount);
        map.put("expiration", time);
        map.put("title", hbzt);
        map.put("schoolId", AccountUtils.getSchoolId(getActivity()));
        map.put("schoolName", AccountUtils.getSchoolName(getActivity()));
        map.put("skinId", themeId);
        map.put("havepic", "1");

        Map<String, File> fileMap = new HashMap<>();
        fileMap.put(System.currentTimeMillis() + ".jpg", f);

        OkHttpUtils.post().url(HttpAddress.SENDREDPAG).params(map).files(name, fileMap).params(map).build().execute(new StringCallback() {


            @Override
            public void onError(Call call, Exception e, int id) {
                ll_loading.setVisibility(ll_loading.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                String json = response;
                Gson gson = new Gson();
                RedPackageResponse fromJson = gson.fromJson(json,
                        RedPackageResponse.class);
                if (fromJson != null) {
                    if ("1".equals(fromJson.state)) {
                        Log.e("test", "发红包成功");
                        redid = fromJson.redId;

                        ShareRedpackage();
                    } else {
                        Toast.makeText(getActivity(), "服务器开小差了", Toast.LENGTH_SHORT).show();
                    }
                }
                ll_loading.setVisibility(ll_loading.GONE);
            }
        });
    }


    private void ShareRedpackage() {

        if (redid == null || "".equals(redid)) {

            Toast.makeText(getActivity(), "服务器开小差了,请重试", Toast.LENGTH_SHORT).show();
            return;
        }
        if (hbzt == null || "".equals(hbzt)) {
            hbzt = "学有所成,前程似锦!";
        }

        MobSDK.init(getActivity(), "12c24ea0b59b0",
                "aae63565fbd69b1acbfcdd0d5ac0b35c");
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

            @Override
            public void onShare(Platform platform, ShareParams paramsToShare) {

                if (SinaWeibo.NAME.equals(platform.getName())) {
                    paramsToShare.setTitle("分享");
                    paramsToShare.setTitleUrl(HttpAddress.TESTREDPAG
                            + "?rid=" + redid);
                    paramsToShare.setTitle("来自"
                            + AccountUtils.getSchoolName(getActivity())
                            + "学校的红包");
                    paramsToShare.setText(hbzt);
                    paramsToShare
                            .setImageUrl(logo);
                    paramsToShare.setUrl(HttpAddress.TESTREDPAG
                            + "?rid=" + redid);
                    paramsToShare.setComment("");
                    paramsToShare.setSite("金牌君");
                    paramsToShare.setSiteUrl(HttpAddress.TESTREDPAG
                            + "?rid=" + redid);
                } else {
                    paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                    paramsToShare.setTitle("分享");
                    paramsToShare.setTitleUrl(HttpAddress.TESTREDPAG
                            + "?rid=" + redid);
                    paramsToShare.setTitle("来自"
                            + AccountUtils.getSchoolName(getActivity())
                            + "学校的红包");
                    paramsToShare.setText(hbzt);
                    paramsToShare
                            .setImageUrl(logo);
                    paramsToShare.setUrl(HttpAddress.TESTREDPAG
                            + "?rid=" + redid);
                    paramsToShare.setComment("");
                    paramsToShare.setSite("金牌君");
                    paramsToShare.setSiteUrl(HttpAddress.TESTREDPAG
                            + "?rid=" + redid);

                }
            }
        });
        oks.show(getActivity());
    }

    /**
     * 无图片红包
     */
    private void creatRedPackage() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("rtype", "1");
        map.put("c", AccountUtils.getAccount(getActivity()));
        map.put("role", AccountUtils.getRole(getActivity()));
        map.put("money", money);
        map.put("persons", redCount);
        map.put("expiration", time);
        map.put("title", hbzt);
        map.put("schoolId", AccountUtils.getSchoolId(getActivity()));
        map.put("schoolName", AccountUtils.getSchoolName(getActivity()));
        map.put("skinId", themeId);
        map.put("havepic", "0");

        HttpUtils.post(HttpAddress.SENDREDPAG, map, this,
                new HttpCallBack<RedPackageResponse>() {

                    @Override
                    public void onSuccess(RedPackageResponse info) {
                        if (info != null) {
                            if ("1".equals(info.state)) {
                                Log.e("test", "发红包成功");
                                redid = info.redId;

                                ShareRedpackage();

                            } else {
                                Toast.makeText(getActivity(), "服务器开小差了", Toast.LENGTH_SHORT).show();
                            }
                        }
                        ll_loading.setVisibility(ll_loading.GONE);
                    }

                    @Override
                    public void onError(String e) {
                        ll_loading.setVisibility(ll_loading.GONE);
                    }
                });
    }


    // 请保证每个人至少能得到一块钱红包
    private void moneydialog() {
        AlertDialogUtil.showAlertDialog(true, getActivity(),
                "您输入的红包金额必须保证每人最少可领取1元", new AlertDialogUtil.onListener() {
                    @Override
                    public void onClickOk() {
                    }

                    @Override
                    public void onClickDismiss() {

                    }
                });
    }
}
